module.exports = {
  blankMatrix(size) {
    let newMatrix = []
    for (let i = 0; i < size; i++) {
      newMatrix.push([])
    }
    return newMatrix
  },

  randerIndex(length) {
    const number_list = [...Array.from({
      length: length
    }, (i, idx) => idx + 1)]
    let index = 0
    let index_idx = Math.ceil(length / 2)
    for (let i = 0; i < index_idx; i++) {
      index = this.randomIndex(length);
      [number_list[0], number_list[index]] = [number_list[index], number_list[0]]
    }
    return number_list
  },

  randomIndex(length) {
    return Math.floor(Math.random() * length)
  },

  makeDigits(base, length_idx) {
    let colLists = this.blankMatrix(length_idx)
    let areaLists = this.blankMatrix(base)
    let number_list = this.randerIndex(length_idx)
    let i = 0,
      j = 0,
      areaIndex = 0,
      count = 0,
      error = false,
      first = 0
    for (i = 0; i < length_idx; i++) {
      colLists[i].push(number_list[i])
    }
    switch (base) {
      case 3:
        areaLists[0] = number_list.slice(0, 3)
        areaLists[1] = number_list.slice(3, 6)
        areaLists[2] = number_list.slice(6)
        break
      case 2:
        areaLists[0] = number_list.slice(0, 2)
        areaLists[1] = number_list.slice(2)
        break
    }
    for (i = 0; i < length_idx - 1; i++) {
      number_list = this.randerIndex(length_idx)
      if (i % base == (base - 1)) {
        areaLists = this.blankMatrix(base)
      }
      for (j = 0; j < length_idx; j++) {
        areaIndex = Math.floor(j / base)
        count = 0
        error = false
        while (colLists[j].includes(number_list[0]) || areaLists[areaIndex].includes(number_list[0])) {
          if (++count >= number_list.length) {
            error = true
            break
          }
          number_list.push(number_list.shift())
        }
        if (error) {
          return false
        }
        first = number_list.shift()
        colLists[j].push(first)
        areaLists[areaIndex].push(first)
      }
    }
    return colLists
  },
}